package service

import (
	"e_mall_server/dao/mysql"
	"e_mall_server/models"
	"errors"
)

/**
 * @Author: zhaobin
 * @Description TODO
 * @Date: 2022-05-09 11:46
 */

// GetGoodsCateList 获取商品分类列表接口
func GetGoodsCateList(query map[string]interface{}) ([]models.GoodsCate, error) {
	return mysql.GetGoodsCateList(query)
}

// AddGoodsCate 添加商品分类信息
func AddGoodsCate(GoodsCate *models.GoodsCate) error {
	return mysql.AddGoodsCate(GoodsCate)
}

// UpdateGoodsCate 修改商品分类信息
func UpdateGoodsCate(GoodsCate *models.GoodsCate) int64 {
	return mysql.UpdateGoodsCate(GoodsCate)
}

// DeleteGoodsCateById 通过商品分类id删除商品分类数据
func DeleteGoodsCateById(id int64) (int64, error) {
	// 判断该商品分类是不是顶级模块
	goodsCate, _ := mysql.GetGoodsCateDetailById(id)
	var count int64
	if goodsCate.ParentId == 0 { //顶级模块
		goodsCateList := mysql.GetGoodsCateListByParentId(goodsCate.ParentId)
		if len(goodsCateList) > 0 {
			return 0, errors.New("当前模块下面有菜单或者操作，请删除菜单或者操作以后再来删除这个数据")
		} else {
			count = mysql.DeleteGoodsCateById(id)
		}
	} else {
		count = mysql.DeleteGoodsCateById(id)
	}

	return count, nil
}

// GetGoodsCateDetailById 通过商品分类id获取商品分类详细信息
func GetGoodsCateDetailById(id int64) (models.GoodsCate, error) {
	return mysql.GetGoodsCateDetailById(id)
}

// GetGoodsCateParentId 如果是二级分类则返回其parent_id，否则id不变
func GetGoodsCateParentId(id int64) int64 {
	if id == 0 {
		return id
	}
	goodsCate, _ := mysql.GetGoodsCateDetailById(id)
	if goodsCate.Level == 1 {
		return id
	} else {
		return goodsCate.ParentId
	}
}
